<?php
namespace Seller\Controller;
use Seller\Logic\GoodsLogic;
use Think\AjaxPage;
use Think\Db;
use Think\Exception;
use Think\Log;
use Think\Page;
use PHPExcel_Cell;
use PHPExcel_IOFactory;
use WXAPI\Controller\IdentificationController;
 
class GoodsController extends BaseController {
    /**
     * 获取商品分类 的帅选规格 复选框 
     */
    public function ajaxGetSpecList(){
        $GoodsLogic = new GoodsLogic();
        $_REQUEST['category_id'] = $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0;
        $filter_spec = M('GoodsCategory')->where("id = ".$_REQUEST['category_id'])->getField('filter_spec');        
        $filter_spec_arr = explode(',',$filter_spec);        
        $str = $GoodsLogic->GetSpecCheckboxList($_REQUEST['type_id'],$filter_spec_arr);  
        $str = $str ? $str : '没有可帅选的商品规格';
        exit($str);        
    }
 
    /**
     * 获取商品分类 的帅选属性 复选框
     */
    public function ajaxGetAttrList(){
        $GoodsLogic = new GoodsLogic();
        $_REQUEST['category_id'] = $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0;
        $filter_attr = M('GoodsCategory')->where("id = ".$_REQUEST['category_id'])->getField('filter_attr');        
        $filter_attr_arr = explode(',',$filter_attr);        
        $str = $GoodsLogic->GetAttrCheckboxList($_REQUEST['type_id'],$filter_attr_arr);          
        $str = $str ? $str : '没有可筛选的商品属性';
        exit($str);        
    }    
    
    /**
     * 删除分类
     */
    public function delGoodsCategory(){
        // 判断子分类
        $GoodsCategory = M("GoodsCategory");
        $count = $GoodsCategory->where("parent_id = {$_GET['id']}")->count("id");   
        $count > 0 && $this->error('该分类下还有分类不得删除!',U('Admin/Goods/categoryList'));
        // 判断是否存在商品
        $goods_count = M('Goods')->where("cat_id = {$_GET['id']}")->count('1');
        $goods_count > 0 && $this->error('该分类下有商品不得删除!',U('Admin/Goods/categoryList'));
        // 删除分类
        $GoodsCategory->where("id = {$_GET['id']}")->delete();   
        $this->success("操作成功!!!",U('Admin/Goods/categoryList'));
    }
    
   
    /**
     *  商品列表
     */
    public function goodsList(){
        checkIsBack();
        $store_goods_class_list = M('store_goods_class')->where("parent_id = 0 and store_id = ".STORE_ID)->select();
        $this->assign('store_goods_class_list',$store_goods_class_list);        
        $this->display();
    }
    /**
     *  商家分类列表
     */
    public function store_cat_id1(){
        $cat_id1 = I('cat_id1');
        $catList2 = M('store_goods_class')->where(['parent_id'=>$cat_id1])->select();
        $this->ajaxReturn(['data'=>$catList2]);
    }
    
    
    
    /*
    *活动
    */
    public function promGoodsList(){
        checkIsBack();
        $store_goods_class_list = M('store_goods_class')->where("parent_id = 0 and store_id = ".STORE_ID)->select();
        $this->assign('store_goods_class_list',$store_goods_class_list);        
        $this->display();
    }
    /**
     * 活动商品
     * */
    public function ajaxpromGoodsList(){
        $time = time();
        $where = [];
        $key_word = I('key_word');
        if($key_word)
        {
            $where = "(goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
        

			
       
//        $where .= " and is_pint = 0 ";
        $count = M('goods a')
			->field('a.*,b.expression')
			->join('ty_prom_goods b on a.prom_id=b.id')
			->where(array('a.store_id'=>STORE_ID,"a.is_on_sale"=>1,"a.is_delete"=>0,'a.goods_state'=>1))
			->where('a.prom_id>0 and '.$time.'>b.start_time and '.$time.'< b.end_time')
			->where($where)
			->count();
        $Page  = new AjaxPage($count,20);
       
              $goodsList = M('goods a')
			->field('a.*,b.expression')
			->join('ty_prom_goods b on a.prom_id=b.id')
			->where(array('a.store_id'=>STORE_ID,"a.is_on_sale"=>1,"a.is_delete"=>0,'a.goods_state'=>1))
			->where('a.prom_id>0 and '.$time.'>b.start_time and '.$time.'< b.end_time')
			->where($where)
			->order('prom_sort','ASC')
			->limit($Page->firstRow.','.$Page->listRows)
			->select();
			
			
        // $goodsList = $model->where($where)->order('prom_sort','DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach($goodsList as $key=>$v){
            $goodsList[$key]['kucun']=M('spec_goods_price')->where('goods_id='.$v['goods_id'])->order('store_count asc')->getField('store_count');
            $goodsList[$key]['zhuangtai']=M('store_msg')->where('goods_id='.$v['goods_id'])->order('sm_id desc')->getField('content');

            $goodsList[$key]['original_img'] = C('MYOSS')['url2'].$v['original_img'];
            $huodong='';
            if($v['prom_id']>0){
                $hd=\M('prom_goods')->field('type,expression')->where("end_time>$time and start_time<$time and id=".$v['prom_id'])->find();
                if($hd)
                    $huodong=huodong_name($hd['type'],$hd['expression']);
            }
            $goodsList[$key]["huodong"]=$huodong;

            //重写排序
            $pd_max=M('spec_item')->where("store_id = ".STORE_ID." and goods_id =".$v['goods_id'])->max('sort');
            if($pd_max==0){
                $order_sort=M('spec_item')->field('id,goods_id')->where("store_id = ".STORE_ID." and goods_id =".$v['goods_id'])->order('id asc')->select();
                $ii=0;
                foreach($order_sort as $vs){
                    M('spec_item')->where("id = ".$vs['id']." and goods_id =".$vs['goods_id'])->setField('sort',$ii);
                    $ii++;
                }
            }

        }

        cachePage($Page);
        $show = $Page->show();
        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $catListLast = M('store_goods_class')->where("store_id = ".STORE_ID)->select();
        $this->assign('catListLast',$catListLast);
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    /**
     *  商品列表
     */
    public function trash(){
        checkIsBack();      
        $this->display();
    } 
    /**
     *  商品列表
     */
    public function ajaxGoodsList(){
        $where = "store_id = ".STORE_ID; // 搜索条件
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;
        (I('store_cat_id1') !== '') && $where = "$where and store_cat_id1 = ".I('store_cat_id1');
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale');
        $goods_state = I('goods_state'); // 商品状态  0待审核 1审核通过 2审核失败  3违规下架
		
        ($goods_state !== '') && $where = "$where and goods_state in ($goods_state) ";
		
		//tianxin100  新增商品回收站功能
		$is_delete =  $_GET["is_delete"]; // 商品状态  0待审核 1审核通过 2审核失败  3违规下架 
		if($is_delete){
			$where = "$where and is_delete = $is_delete ";
		}else{
			
			$where = "$where and is_delete = 0 ";
		}
		//tianxin100  新增商品回收站功能
        
	
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
            $where .= " and is_pint = 0 ";
        $model = M('Goods');
		
        $count = $model->where($where)->count();

        $Page  = new AjaxPage($count,20);
        
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        //是否从缓存中获取Page
        if(session('is_back')==1){
            $Page = getPageFromCache();
            //重置获取条件
            delIsBack();
        }
        
		$now=\time();
        $goodsList = $model->field('ty_goods.*,(select ty_spec_goods_price.store_count from ty_spec_goods_price  where ty_spec_goods_price.goods_id=ty_goods.goods_id order by ty_spec_goods_price.store_count asc limit 1) as store_count')->where($where)->order($order_str.', goods_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		foreach($goodsList as $key=>$v){
			$goodsList[$key]['kucun']=M('spec_goods_price')->where('goods_id='.$v['goods_id'])->order('store_count asc')->getField('store_count');
			$goodsList[$key]['zhuangtai']=M('store_msg')->where('goods_id='.$v['goods_id'])->order('sm_id desc')->getField('content');

             $goodsList[$key]['original_img'] = C('MYOSS')['url2'].$v['original_img'];
			$huodong='';
			if($v['prom_id']>0){
				$hd=\M('prom_goods')->field('type,expression')->where("end_time>$now and start_time<$now and id=".$v['prom_id'])->find();
				if($hd)
				$huodong=huodong_name($hd['type'],$hd['expression']);
			}
			$goodsList[$key]["huodong"]=$huodong;
			
			//重写排序
			$pd_max=M('spec_item')->where("store_id = ".STORE_ID." and goods_id =".$v['goods_id'])->max('sort');
			if($pd_max==0){
				$order_sort=M('spec_item')->field('id,goods_id')->where("store_id = ".STORE_ID." and goods_id =".$v['goods_id'])->order('id asc')->select();
				$ii=0;
				foreach($order_sort as $vs){
					M('spec_item')->where("id = ".$vs['id']." and goods_id =".$vs['goods_id'])->setField('sort',$ii);
					$ii++;
				}
			}
			
		}

        cachePage($Page);
        $show = $Page->show();
        
        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $catListLast = M('store_goods_class')->where("store_id = ".STORE_ID.' and parent_id = 0')->select();
        
        // dump($catListLast);
        $this->assign('catListLast',$catListLast);
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();         
    }
	
    public function fenlei_sousuo(){
		$key=I('key');
		if($key){
		$fenlei=M('goods_category a')
		->field('a.id,a.name,a.level,
		b.id idb,b.parent_id,b.name nameb')
		->join('ty_goods_category b on a.parent_id=b.id','LEFT')
		->where('a.name like "%'.$key.'%"')->limit(15)->select();
		
		foreach($fenlei as $v){
			if($v['level']==3){
				$top1=M('goods_category')->where('id='.$v['parent_id'])->find();
				echo '<li rel="'.$top1['id'].','.$v['idb'].','.$v['id'].'">'.$top1['name'].' > '.$v['nameb'].' > '.$v['name'].'</li>';
			}elseif($v['level']==2){
				echo '<li rel="'.$v['idb'].','.$v['id'].'">'.$v['nameb'].' > '.$v['name'].'</li>';
			}else{
				echo '<li rel="'.$v['id'].'">'.$v['name'].'</li>';
			}
			
		}
		}
		exit;
	}
   /**
     * 添加修改商品
     */
    public function addEditGoods(){
        $GoodsLogic = new GoodsLogic();
		$basic=tpCache("basic");
        $Goods = D('Admin/Goods');
        $goods_id = I('goods_id',0);
        $type = $goods_id > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        if($goods_id > 0)
        {
            $c = M('goods')->where("goods_id = $goods_id and store_id = ".STORE_ID)->count(); // 如果为修改查看有多少个商品
            if($c == 0)
                $this->error("非法操作",U('Goods/goodsList'));
        }
        //ajax提交验证
        if(($_GET['is_ajax'] == 1) && IS_POST)
        {
            C('TOKEN_ON',false);  // 是否开启令牌验证
            if(!$Goods->create(NULL,$type))// 根据表单提交的POST数据创建数据对象
            {
                //  提交的数据为空时执行的if 
                $error = $Goods->getError();
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                );
                $this->ajaxReturn(json_encode($return_arr));
            }else {
                try {
                    M()->startTrans();
                    $Goods->on_time = time(); // 上架时间
                    $cat_id3 = I('cat_id3',0);
                    $_POST['extend_cat_id_2'] && ($Goods->extend_cat_id = I('extend_cat_id_2'));
                    $_POST['extend_cat_id_3'] && ($Goods->extend_cat_id = I('extend_cat_id_3'));
                    $Goods->shipping_area_ids = implode(',',$_POST['shipping_area_ids']);
                    $Goods->shipping_area_ids = $Goods->shipping_area_ids ? $Goods->shipping_area_ids : '';

                    $store_info = M('store')->where(array('store_id'=>STORE_ID))->find();
                    $myitem = I('item'); //处理默认价格
                    $myitem=array_slice($myitem,0,1);
                    $myitem=array_shift($myitem);

                    $Goods->cost_price = 0;
                    $Goods->shop_price=$myitem['price'];
//                    $Goods->goods_type = $type_id ? $type_id : 0;
                    $Goods->store_id = STORE_ID; // 店家id

                    $goods_limit = M('store_grade')->where(array('sg_id'=>$store_info['grade_id']))->getField('sg_goods_limit');

                    $goods_all_number=M('goods')->where(array('store_id'=>STORE_ID))->count();
                    if(!empty($goods_limit)){

                        if($goods_limit<$goods_all_number){

                            $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '超过上传数量，最多可传商品数量为：'.$goods_limit,'data'  =>'')));
                        }
                    }

                    if($Goods->distribut > ($Goods->shop_price / 2))
                        $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '分销的分成金额不得超过商品金额的50%','data'  =>'')));
                    $Goods->fenbu_id = \session('fenbu_ids');

                    if ($type == 2)
                    {
                        $old_goods_name = M('goods')->field('goods_name,keywords,original_img')->where(['goods_id'=>$goods_id])->find(); //获取旧产品名称

                        // if(I('goods_name') != $old_goods_name['goods_name'] ){
                        //     $Goods->goods_state = 0;
                        // }
                        //$Goods->goods_state =1; //修改不用审核
                        //$Goods->is_on_sale = 1;
                        if(empty($_POST['myitems'])){
                            $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '商品规格不能为空','data'  =>'')));
                        }
                        $old_goods_name = M('goods')->field('goods_name,keywords,original_img')->where(['goods_id'=>$goods_id])->find(); //获取旧产品名称
                        // if( I('keywords') != $old_goods_name['keywords'] || I('original_img') != $old_goods_name['original_img']){
                        //     $Goods->goods_state = 0;
                        // }
                        if(M('Goods')->where(array('goods_id'=>$goods_id,'store_id'=>STORE_ID))->count()>0){
                            // 修改商品后购物车的商品价格也修改一下
                            $Goods->save(); // 编辑数据到数据库

                            $spec_item = M('spec_item a')->join('ty_spec w ON a.spec_id = w.id')->where(array('a.goods_id'=>$goods_id,'a.store_id'=>STORE_ID))->select();
                            if($spec_item){
                                if(M('goods_type')->where(array('id'=>$spec_item[0]['goods_type_id']))->count()<=0){
                                    $c_data['id'] = $spec_item[0]['goods_type_id'];
                                    $c_data['name'] = '类型';
                                    $c_data['store_id'] = STORE_ID;
                                    M('goods_type')->add($c_data);
                                    unset($c_data);
                                }
                            }
                        }else{
                            $this->ajaxReturn(array('status' => -1,'msg'=> '非法操作'),'JSON');
                        }
                        //$tiaozhuan=U('Goods/goodsList',array('goods_state'=>1,'is_back'=>1));
                        $tiaozhuan='/index.php/Seller/Goods/addEditGoods/goods_id/'.$goods_id;
                    }
                    else
                    {
                        $Goods->yijia_quyu = $store_info['yijia_quyu'];
                        if(empty($store_info['sale_num'])){
                            $store_info['sale_num'] = 0;
                        }
                        $Goods->sales_sum = $store_info['sale_num'];
                        $Goods->points =  $store_info['koudian'];
                        if($store_info['goods_examine']){
                            $Goods->goods_state = 0; // 待审核
                            $Goods->is_on_sale = 0; // 未上架 //20181130  tianxin100修复未审核商品上架问题

                        }else{
                            $Goods->goods_state = 1; // 出售中
                        }

                        if(empty($_POST['myitems'])){
                            $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '商品规格不能为空','data'  =>'')));
                        }

                        $goods_id = $Goods->add(); // 新增数据到数据库
                        $mydata['goods_id'] = $goods_id;
                        M('spec_item')->data($mydata)->where('id in('.$_POST['myitems'].')')->save();
                        $tiaozhuan=U('Goods/goodsList');
                    }
                    $Goods->afterSave($goods_id,STORE_ID);

//                    $GoodsLogic->saveGoodsAttr($goods_id,$type_id,STORE_ID); // 处理商品 属性
                    $GoodsLogic->saveGoodsAttr($goods_id,$_POST['goods_type'],STORE_ID); // 处理商品 属性
                    cart_price($goods_id);


                    //更新产品最低价
                    $minPrice = M('spec_goods_price')->where(['price'=>['gt',0.01],'store_count'=>['gt',0]])->where('goods_id=' . $goods_id)->min('price');

                    if($minPrice){
                        M('goods')->where('goods_id=' . $goods_id)->save(['shop_price' => $minPrice]);
                    }

                    //上传抠图后的比较图 end
                    
                    $return_arr = array(
                        'status' => 1,
                        'msg'   => '操作成功',
                        'data'  => array('url'=>$tiaozhuan),
                    );
                    //重定向, 调整之前URL是设置参数获取方式
                    session("is_back" , 1);

                    M()->commit();
                }catch (Exception $e){
                    Log::record($e->getMessage(),'ERR');
                    $return_arr = array(
                        'status' => 0,
                        'msg'   => '操作失败',
                        'data'  => array('url'=>$tiaozhuan),
                    );

                    M()->rollback();
                }

                $this->ajaxReturn(json_encode($return_arr));
               // form表单提交
               // C('TOKEN_ON',true);


                }  
            }

            $goodsInfo =M('Goods')->where('goods_id='.I('GET.goods_id',0))->find();

            $store = M('store')->where(array('store_id'=>STORE_ID))->find();
            
            $cat_list = M('goods_category')->where("parent_id = 0")->select();//自营店已绑定所有分类
                                 
            $store_goods_class_list = M('store_goods_class')->where("parent_id = 0 and store_id = ".STORE_ID)->select(); //店铺内部分类                      
            $brandList = $GoodsLogic->getSortBrands();
            $goodsType = M("GoodsType")->where(array('store_id'=>STORE_ID))->select(); //获取当前店铺的商品类型

            $suppliersList = M("suppliers")->select();
            $plugin_shipping = M('plugin')->where(array('type'=>array('eq','shipping')))->select();//插件物流
            $shipping_area = D('shipping_area')->getShippingArea(STORE_ID);//配送区域
            $goods_shipping_area_ids = explode(',',$goodsInfo['shipping_area_ids']);
            $this->assign('goods_shipping_area_ids',$goods_shipping_area_ids);
            $this->assign('shipping_area',$shipping_area);
            $this->assign('plugin_shipping',$plugin_shipping);
            $this->assign('cat_list',$cat_list);
            $this->assign('store_goods_class_list',$store_goods_class_list);
            $this->assign('brandList',$brandList);
            $this->assign('goodsType',$goodsType);
            $this->assign('suppliersList',$suppliersList);
// 			$goodsInfo['guanlian']=\str_replace(',,',',',$goodsInfo['guanlian']);
		if(!empty($goodsInfo['guanlian'])){
			    $goodsInfo['guanlian'] = explode(',',$goodsInfo['guanlian']);
			    $guanlian = '';
			    foreach ($goodsInfo['guanlian'] as $k=>$v){
			        if(empty($v)){
			            unset($v);
			        }else{
			            $guanlian .= $v.',';
			        }
			    }
			    $goodsInfo['guanlian'] = substr($guanlian, 0, -1);
    			$goodsInfo['guanlian_list']=M("Goods")
    			->field('goods_id,goods_name,store_count,shop_price')
    			->where('goods_id in('.$goodsInfo['guanlian'].')')
    			->order('goods_id desc')
    			->select();
			}
            $this->assign('goodsInfo',$goodsInfo);  // 商品详情
        // 20181020 增加相片排序 亮 START
//        $goodsImages = M("GoodsImages")->where('goods_id ='.I('GET.goods_id',0))->order("sort_id asc")->select();
        // 20181020 增加相片排序 亮 END
        if(!empty(I('GET.goods_id'))){
            $goodsImages = M("GoodsImages")->where('goods_id ='.I('GET.goods_id'))->order("sort_id asc")->select();
        }else{
            $goodsImages=[];
        }
        $this->assign('goodsImages',$goodsImages);  // 商品相册

        $this->initEditor(); // 编辑器
        $this->display('_goods');
    }

    /**
     * 虚拟评价
     */
    public function virtual_comment(){
        $db_prefix = C('DB_PREFIX');
        $goods_id = I('goods_id');
        //ajax提交验证

        if(($_GET['is_ajax'] == 1 && IS_POST))
        {
                  $model = M("comment");
                  $_POST['store_id'] = STORE_ID;
                  $_POST['add_time'] = strtotime($_POST['add_time']) ;
                  $_POST['img'] =json_encode(explode(",",$_POST['img'])) ;
                  $_POST['username'] = $this->get_username();
                  $_POST['goods_rank'] =5;
		  $_POST['service_rank'] =5;
		  $_POST['deliver_rank'] =5;
                  unset($_POST['__hash__']);

                  $id = $model->add($_POST);
                    if ($id){
		    	$comment_count = M('goods')->where(array('goods_id'=>$goods_id))->getField('comment_count');
			$comment_count += 1;
			M('goods')->where(array('goods_id'=>$goods_id))->save(array('comment_count'=>$comment_count));
                        $return_arr = array(
                            'status' => 1,
                            'msg'   => '操作成功',
                            'data'  => array('url'=>U('Goods/virtual_comment',array('goods_id'=>$_POST['goods_id']))),
                        );
                     }else{
                        $return_arr = array(
                        'status' => 0 );
                      }

            $this->ajaxReturn(json_encode($return_arr));
        }
        $this->assign('goods_id',$goods_id);
        $this->display();
    }

   public function get_username ()
    {
        $charts = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        $max = strlen($charts);
         $username = '';
        for($i = 0; $i < 6; $i ++)
        {
            $username .= $charts[mt_rand(0, $max)];
        }
        


        return $username;
    }

    /**
     * 上传评论图片
     */
    public function uploadimage()
    {
        $path = "Public/upload/comment/";
        $path .= date('Y')."/".date('m-d')."/";
        if (!is_dir($path)) { //判断目录是否存在 不存在就创建
            mkdir($path, 0777, true);
        }

        $allow = ["image/jpg","image/jpeg","image/bmp","image/png",];
        if ($_FILES["file"]["error"] > 0) {
            echo "上传错误,错误代码:" . $_FILES["file"]['error'];
            die();
        }

        if (!in_array($_FILES["file"]["type"], $allow)) {
            echo "上传的文件类型不被允许";
            die();
        }

        if ($_FILES['file']['size'] > 5 * 1024 * 1024) {
            exit("上传文件过大");
        }
        $imageName = date("YmdHis", time()) . rand(1111, 9999).".jpg" ;
        $filepath = $path.$imageName;

        if (move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {
            echo json_encode(array("data" => array("url" => "/".$filepath,)));

        }
    }
    /**
     * 删除图片
     */
    public function delUploadimage()
    {
         if ($_POST){
           $img = explode(",",$_POST['img']);
           foreach ($img as $k =>$v){

               if (trim($v) == trim($_POST['index'])){
                  $v= substr($v,1);

                  $res=  unlink($v);

                 if ($res){
                     unset($img[$k]);
                     $img1= implode(",",$img);
                     echo json_encode(array("code"=>1,"img" => $img1));
                 }else{
                     echo json_encode(array("code"=>0,"img" => '',));
                   }
               }
           }
         }
    }

    /**
     * 上传视频
     */
    public function uploadVideo()
    {
        $path = "Public/upload/video/";
        $path .= date('Y-m-d')."/";
        if (!is_dir($path)) { //判断目录是否存在 不存在就创建
            mkdir($path, 0777, true);
        }

        $allow = ["video/mp4","video/wmv","video/avi","video/rm","video/rmvb","video/swf"];
        if ($_FILES["file"]["error"] > 0) {
            echo "上传错误,错误代码:" . $_FILES["file"]['error'];
            die();
        }

        if (!in_array($_FILES["file"]["type"], $allow)) {
            echo "上传的文件类型不被允许";
            die();
        }

        if ($_FILES['file']['size'] > 8 * 1024 * 1024) {
            exit("上传文件过大");
        }
        $imageName = date("YmdHis", time()) . rand(1111, 9999).".mp4" ;
        $filepath = $path.$imageName;

        if (move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {

                echo json_encode(array("url" => "/".$filepath));

        }
    }
 
	/*
	 ajax 修改指定表数据字段  一般修改状态 比如 是否推荐 是否开启 等 图标切换的
	 table,id_name,id_value,field,value
	*/ 
    public function changeTableVal(){
        $table = I('table'); // 表名
        $id_name = I('id_name'); // 表主键id名
        $id_value = I('id_value'); // 表主键id值
        $field  = I('field'); // 修改哪个字段
        $value  = I('value'); // 修改字段值
		if($field=="is_on_sale"&&$value==1){
			//如果是修改上下架，判断商品是否在审核中，未审核的不能上架 20181130  tianxin100
			$goods_state = M($table)->where("$id_name = $id_value and store_id = ".STORE_ID)->getField('goods_state'); // 找到这个分类对应的type_id
			if($goods_state ==1){
				
				M($table)->where("$id_name = $id_value and store_id = ".STORE_ID)->save(array($field=>$value)); // 根据条件保存修改的数据
			}
			
		}else{
			
			M($table)->where("$id_name = $id_value and store_id = ".STORE_ID)->save(array($field=>$value)); // 根据条件保存修改的数据
		}
    }
      
    /**
     * 更改指定表的指定字段
     */
    public function updateField(){
        $primary = array(
                'goods' => 'goods_id',                                
                'goods_attribute' => 'attr_id',
        	'ad' =>'ad_id',     
        );
        $id = I('id',0);
        $field = I('field');
        $value= I('value');      
        M($_POST['table'])->where("{$primary[$_POST['table']]} = $id and store_id = ".STORE_ID)->save(array($field =>$value));
        $return_arr = array(
            'status' => 1,
            'msg'   => '操作成功',                        
            'data'  => array('url'=>U('Goods/goodsAttributeList')),
        );
        $this->ajaxReturn(json_encode($return_arr));
    }
    /**
     * 动态获取商品属性输入框 根据不同的数据返回不同的输入框类型
     */
    public function ajaxGetAttrInput(){
        $cat_id3 = I('cat_id3',0);
        $goods_id = I('goods_id',0);
        empty($cat_id3) && exit('');       
        $type_id = M('goods_category')->where("id = $cat_id3")->getField('type_id'); // 找到这个分类对应的type_id
        empty($type_id) && exit('');
        $GoodsLogic = new GoodsLogic();
        $str = $GoodsLogic->getAttrInput($goods_id,$type_id);
        exit($str);
    }
    public function ajaxGetAttrInput_tianxin(){
        $cat_id3 = I('cat_id3',0);
        $goods_id = I('goods_id',0);
        empty($cat_id3) && exit(''); 
		
		$store_id=$_SESSION['store_id'];
		$type_id = M('store_goods_class')->where("cat_id = '$cat_id3'  AND store_id='$store_id'")->getField('type_id'); // 已经改成联动菜单

        empty($type_id) && exit('');
        $GoodsLogic = new GoodsLogic();

        $str = $GoodsLogic->getAttrInput($goods_id,$type_id);
        exit($str);
    }       
    /**
     * 删除商品
     */
    public function delGoods()
    {
        $goods_id = $_GET['id'];
        $error = '';
        
        // 判断此商品是否有订单
        $c1 = M('OrderGoods')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有订单,不得删除! <br/>';
        
        
         // 商品团购
        $c1 = M('group_buy')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有团购,不得删除! <br/>';   
        
         // 商品退货记录
        $c1 = M('return_goods')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有退货记录,不得删除! <br/>';
        
        if($error)
        {
            $return_arr = array('status' => -1,'msg' =>$error,'data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
            $this->ajaxReturn(json_encode($return_arr));            
        }
        
        // 删除此商品        
        $result = M("Goods")->where("goods_id = $goods_id and store_id = ".STORE_ID)->delete();  //商品表
        if($result)
        {
            M("cart")->where('goods_id ='.$goods_id)->delete();  // 购物车
            M("comment")->where('goods_id ='.$goods_id)->delete();  //商品评论
            M("goods_consult")->where('goods_id ='.$goods_id)->delete();  //商品咨询
            M("goods_images")->where('goods_id ='.$goods_id)->delete();  //商品相册
            M("spec_goods_price")->where('goods_id ='.$goods_id)->delete();  //商品规格
            M("spec_image")->where('goods_id ='.$goods_id)->delete();  //商品规格图片
            M("goods_attr")->where('goods_id ='.$goods_id)->delete();  //商品属性     
            M("goods_collect")->where('goods_id ='.$goods_id)->delete();  //商品收藏          
        }            
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
        $this->ajaxReturn(json_encode($return_arr));
    }
	
	/*
	
	处理商品加入回收站
	*/
	public function doneTrash(){
		
        $goods_id = $_GET['id'];
        $error = '';		
        $value= I('value');      
		M("goods")->where(" goods_id = ".$goods_id)->save(array("is_delete" =>1,"is_on_sale"=>0));		
        $return_arr = array('status' => 1,'msg' => '加入回收站成功','data'  =>'',);        
        $this->ajaxReturn(json_encode($return_arr));		
		
	}
 
	/*
	
	处理商品恢复
	*/
	public   function rollBack(){
		
        $goods_id = $_GET['id'];
        $error = '';		
        $value= I('value');      
		M("goods")->where(" goods_id = ".$goods_id)->save(array("is_delete" =>0));		
        $return_arr = array('status' => 1,'msg' => '加入回收站成功','data'  =>'',);        
        $this->ajaxReturn(json_encode($return_arr));		
		
	} 
    /**
     * ajax 获取 品牌列表
     */
    public function getBrandByCat(){
        $db_prefix = C('DB_PREFIX');
        $cat_id = I('cat_id');
        $level = I('l');
        $type_id = I('type_id');        
        
        if($type_id)
            $list = M('brand')->join("left join {$db_prefix}brand_type on {$db_prefix}brand.id = {$db_prefix}brand_type.brand_id and  type_id = $type_id")->order('id')->select();    
        else    
            $list = M('brand')->order('id')->select();        
        
        $goods_category_list = M('goods_category')->where("id in(select cat_id1 from {$db_prefix}brand) ")->getField("id,name,parent_id");
        $goods_category_list[0] = array('id'=>0, 'name'=>'默认');
        asort($goods_category_list);
        $this->assign('goods_category_list',$goods_category_list);        
        $this->assign('type_id',$type_id);
        $this->assign('list',$list);
        $this->display();
    }
    
    
    /**
     * ajax 获取 规格列表
     */
    public function getSpecByCat(){
        
        $db_prefix = C('DB_PREFIX');
        $cat_id = I('cat_id');
        $level = I('l');
        $type_id = I('type_id');
       
        if($type_id)            
            $list = M('spec')->join("left join {$db_prefix}spec_type on {$db_prefix}spec.id = {$db_prefix}spec_type.spec_id  and  type_id = $type_id")->order('id')->select();
        else    
            $list = M('spec')->order('id')->select();        
                       
        $goods_category_list = M('goods_category')->where("id in(select cat_id1 from {$db_prefix}spec) ")->getField("id,name,parent_id");
        $goods_category_list[0] = array('id'=>0, 'name'=>'默认');
        asort($goods_category_list);               
        $this->assign('goods_category_list',$goods_category_list);
        $this->assign('type_id',$type_id);
        $this->assign('list',$list);
        $this->display();
    }    
     
    /**
     * 初始化编辑器链接     
     * 本编辑器参考 地址 http://fex.baidu.com/ueditor/
     */
    private function initEditor()
    {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp',array('savepath'=>'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp',array('savepath'=>'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp',array('savepath'=>'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp',array('savepath'=>'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage',array('savepath'=>'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager',array('savepath'=>'article'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie',array('savepath'=>'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }    
     
    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect(){
        $goods_id = I('goods_id',0);
        $cat_id3 = I('cat_id3',0);
        empty($cat_id3) && exit('');
        $goods_id = $goods_id ? $goods_id : 0;
        
        $type_id = M('goods_category')->where("id = $cat_id3")->getField('type_id'); // 找到这个分类对应的type_id
        empty($type_id) && exit('');
        $spec_id_arr = M('spec_type')->where("type_id = $type_id")->getField('spec_id',true); // 找出这个类型的 所有 规格id 
        empty($spec_id_arr) && exit('');
        
        $specList = D('Spec')->where("id in (".  implode(',',$spec_id_arr).") ")->order('`order` desc')->select(); // 找出这个类型的所有规格
        foreach($specList as $k => $v)        
            $specList[$k]['spec_item'] = D('SpecItem')->where("store_id = ".STORE_ID." and spec_id = ".$v['id'])->getField('id,item'); // 获取规格项                
        
        $items_id = M('spec_goods_price')->where("goods_id = $goods_id")->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $items_ids = explode('_', $items_id);       
        
        // 获取商品规格图片                
        if($goods_id)
        {
           $specImageList = M('SpecImage')->where("goods_id = $goods_id")->getField('spec_image_id,src');                 
        }        
        $this->assign('specImageList',$specImageList);
        
        $this->assign('items_ids',$items_ids);
        $this->assign('specList',$specList);
        $this->display('ajax_spec_select');        
    }    
 
    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框shadow
     */
    public function ajaxGetSpecSelect_tianxin(){
        $goods_id = I('goods_id',0);
        $cat_id3 = I('cat_id3',0);
		$mytype=I('mytype',0);
        empty($cat_id3) && exit('');
        $goods_id = $goods_id ? $goods_id : 0;
        $store_id=$_SESSION['store_id'];
        $specList = D('Spec')->where("goods_type_id=$cat_id3  AND store_id='$store_id'")->order('`order` asc')->select(); // 找出这个类型的所有规格
		
		//$items_id = M('spec_goods_price')->where("goods_id = $goods_id")->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");

		$items_id =M('spec_goods_price')->field("key")->where("goods_id =".$goods_id)->select();
		foreach($items_id as $v){
			$myitem_id.=$v['key'].'_';
		}
		$myitem_id=rtrim($myitem_id, "_");
		$items_ids = explode('_', $myitem_id);
		
			foreach($specList as $k => $v){
				$specitem=D('SpecItem')->where("store_id = ".STORE_ID." and spec_id = ".$v['id'])->getField('id,item');
					if($mytype){
						$specList[$k]['spec_item'] =D('SpecItem')->where("store_id = ".STORE_ID." and spec_id = ".$v['id']." and goods_id=".$mytype)->order("sort asc")->getField('id,item'); // 修改获取规格项
					}else{
						$specList[$k]['spec_item'] =D('SpecItem')->where("store_id = ".STORE_ID." and spec_id = ".$v['id']." and goods_id=0")->order("sort asc")->getField('id,item'); // 修改获取规格项
					}
					}

        // 获取商品规格图片
        if($goods_id)
        {
           $specImageList = M('Spec_image')->where("goods_id = $goods_id")->getField('spec_image_id,src');
           foreach ($specImageList as $k=>$item){
               if($item){
                   $specImageList[$k] = $item;
               }
           }
        } 
        $this->assign('specImageList',$specImageList);
		$this->assign('mytype',$mytype);
        $this->assign('items_ids',$items_ids);
        $this->assign('specList',$specList);
        $this->display('ajax_spec_select');
    }  
    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */    
    public function ajaxGetSpecInput(){
         $GoodsLogic = new GoodsLogic();
         $goods_id = I('get.goods_id','');
         $spec_arr = I('spec_arr');
         $str = $GoodsLogic->getSpecInput($goods_id ,$spec_arr,STORE_ID);
         exit($str);   
    }

    /**
     * 商家发布商品时修改的规格
     */
    public function updateSpecItem(){
        $spec_id = I('spec_id',0); // 规格id
        $spec_item = I('spec_item','','trim');// 规格项
        $spec_item_id = I('spec_item_id',0); //规格项 id
		
        
    if(!empty($spec_item_id))
        $id = $spec_item_id;
    else    
        $id = M('spec_item')->where("store_id = ".STORE_ID." and spec_id = $spec_id")->getField('id');
        
        if(empty($id))
        {
             $return_arr = array( 'status' => -1, 'msg' => '规格不存在');
             exit(json_encode($return_arr));
        }
		
        $c = M("spec_goods_price")->where("store_id = ".STORE_ID." and `key` REGEXP '^{$id}_' OR `key` REGEXP '_{$id}_' OR `key` REGEXP '_{$id}$' or `key` = '{$id}'")->count(); // 其他商品用到这个规格不得删除
        if($c)
        {
            $return_arr = array('status' => -1,'msg'=> '此规格其他商品使用中,不得修改');             
             exit(json_encode($return_arr));
        }
		
        M('spec_item')->where("id = $id")->setField('item',$spec_item); //修改规格项
        
        $return_arr = array('status' => 1,'msg'=> '修改成功!');
        exit(json_encode($return_arr));         
    }   
    /**
     * 商家发布商品时添加的规格
     */
    public function addSpecItem(){
        $spec_id = I('spec_id',0); // 规格id
		$goods_id=I('goods_id',0);
        $spec_item = I('spec_item','','trim');// 规格项
        //php检测非法字符的一种方法
        $illegal_character="#['!`~\\\\^=\$\:;<>\]\[{}]#";
        // $illegal_character="#['!`~\/\\\^=\$\:;<>\]\[{}]#";

        if(preg_match($illegal_character,$spec_item)){
            $return_arr = array(
                'status' => -1,
                'msg'   => '规格存在非法符号',
                'data'  =>'',
            );
            exit(json_encode($return_arr));
        }
		$c = M('spec_item')->where("store_id = ".STORE_ID." and item = '$spec_item' and goods_id = '$goods_id' and spec_id = $spec_id")->count();
        if($c > 0)
        {
            $return_arr = array( 
                'status' => -1,
                'msg'   => '规格已经存在',
                'data'  =>'',
             );             
             exit(json_encode($return_arr));
        }        
        $data = array(
            'spec_id'=>$spec_id,
            'item'=>$spec_item,
            'store_id'=>STORE_ID,
			'goods_id'=>$goods_id,
			'sort'=>M('spec_item')->where("store_id = ".STORE_ID." and goods_id = '$goods_id' and spec_id = $spec_id")->max('sort')+1
        );
        M('spec_item')->add($data);
        
        $return_arr = array(
            'status' => 1,
            'msg'   => '添加成功!',
            'data'  =>'',
         );
         exit(json_encode($return_arr));
    }
    
    /**
     * 商家发布商品时删除的规格
     */
    public function delSpecItem(){
        $spec_id = I('spec_id',0); // 规格id
        //$spec_item = I('spec_item','','trim');// 规格项
        $id = I('spec_item_id',0); //规格项 id

        if(empty($id)) 
        {
             exit(json_encode($return_arr));
        }
        $c = M("order_goods")->where("store_id = ".STORE_ID." and `spec_key` REGEXP '^{$id}_' OR `spec_key` REGEXP '_{$id}_' OR `spec_key` REGEXP '_{$id}$' or `spec_key` = '{$id}'")->count(); // 其他订单用到这个规格不得删除
        if($c)
        {
            $return_arr = array('status' => -1,'msg'=> '此规格已有订单,不得删除！点击可取消使用。');
             exit(json_encode($return_arr));
        }

        $specItem =  M('spec_item')->where("id = $id and spec_id= $spec_id")->find();

		
        M('spec_item')->where("id = $id and spec_id= $spec_id")->delete(); // 删除规格项
        M('spec_image')->where("spec_image_id = $id and store_id = ".STORE_ID)->delete(); // 删除规格图片选项


        //删除同步广西  by sofwu start
        $sync_store_name = M('sync_account')->where(['store_id'=>STORE_ID,'tag'=>'guangxi'])->getField('store_name');
        if($sync_store_name){
            $goods = M('goods')->where(['goods_id'=>$specItem['goods_id']])->find();

            $param['store_name'] = $sync_store_name;
            $param['spec_name'] = $specItem['item'];
            $param['goods_name'] = $goods['goods_name'];

            $url = C('SYNC_URL')['guangxi'].'/WXAPI/sync/delGoodsSpec';
            $callback = httpRequest($url,'POST',$param);
            Log::record($callback,'DEBUG');
        }
        //删除同步广西  by sofwu end

        $return_arr = array('status' => 1,'msg'=> '删除成功!');
        exit(json_encode($return_arr)); 
    }    
    /**
     * 商品规格列表    
     */
    public function specList(){               
        $cat_list = M('goods_category')->where("parent_id = 0")->getField('id,name,parent_id'); // 已经改成联动菜单                
        $this->assign('cat_list',$cat_list);        
        $this->display();
    }  
    
    /**
     *  商品规格列表
     */
    public function ajaxSpecList(){ 
        //ob_start('ob_gzhandler'); // 页面压缩输出
        $cat_id3 = I('cat_id3',0); 
        $spec_id = I('spec_id',0);
        $type_id = M('goods_category')->where("id = $cat_id3")->getField('type_id'); // 获取这个分类对应的类型
        if(empty($cat_id3) || empty($type_id)) exit('');
        
        $spec_id_arr = M('spec_type')->where("type_id = $type_id")->getField('spec_id',true); // 获取这个类型所拥有的规格
        if(empty($spec_id_arr)) exit('');
        
        $spec_id = $spec_id ? $spec_id : $spec_id_arr[0]; //没有传值则使用第一个
        
        $specList = M('spec')->where(" id in(".  implode(',', $spec_id_arr).")")->getField('id,name,cat_id1,cat_id2,cat_id3');        
        $specItemList = M('spec_item')->where("store_id = ".STORE_ID." and spec_id = $spec_id")->order('id')->select(); // 获取这个类型所拥有的规格                        
        //I('cat_id1')   && $where = "$where and cat_id1 = ".I('cat_id1') ;                       
        $this->assign('spec_id',$spec_id);
        $this->assign('specList',$specList);
        $this->assign('specItemList',$specItemList);
        $this->display();         
    }  
    /**
     *  批量添加修改规格
     */
    public function batchAddSpecItem(){
        $spec_id = I('spec_id',0);
        $item = I('item'); 
        $spec_item = M('spec_item')->where("store_id = ".STORE_ID."  and spec_id = $spec_id")->getField('id,item');
        foreach($item as $k => $v)
        {            
            $v = trim($v);
            if(empty($v)) continue; // 值不存在 则跳过不处理            
            // 如果spec_id 存在 并且 值不相等 说明值被改动过
            if(array_key_exists($k,$spec_item) && $v != $spec_item[$k])
            {
                M('spec_item')->where("id = $k and store_id = ".STORE_ID)->save(array('item'=>$v));
                // 如果这个key不存在 并且规格项也不存在 说明 需要插入
            }elseif(!array_key_exists($k,$spec_item) && !in_array($v, $spec_item)){
                M('spec_item')->add(array('spec_id'=>$spec_id,'item'=>$v,'store_id'=>STORE_ID));
            }
        }
        $this->success('操作成功!');
    }


    /**
     * 产品批量操作 by 众创织梦-邵
     * @param $id
     */
    public function goods_actions(){
        $action = $_POST['type'];
        $action2 = $_POST['type2'];
        $goods_ids = $_POST['goods_ids'];
        $data = [];
        if(!empty($action)){
            $data['store_cat_id1'] = $action;
        }
        if(!empty($action2)){
            $data['store_cat_id2'] = $action2;
        }
        
        $map['goods_id'] = ['in',$goods_ids];
        M('goods')->where($map)->save($data);
        echo '0';
    }
    
        /**
         * 品牌列表
         */
        public function brandList(){ 
            $model = M("Brand"); 
            $where = " store_id = ".STORE_ID;
            $keyword = I('keyword');
            $keyword && $where.=" and name like '%$keyword%' ";
            $count = $model->where($where)->count();
            $Page  = new Page($count,16);
            $brandList = $model->where($where)->order("`sort` asc")->limit($Page->firstRow.','.$Page->listRows)->select();
            foreach ($brandList as $key=>$v){
                $brandList[$key]['logo'] =  $v['logo'];
            }
            $show  = $Page->show(); 
            $cat_list = M('goods_category')->where("parent_id = 0")->getField('id,name'); // 已经改成联动菜单
            $this->assign('cat_list',$cat_list);       
            $this->assign('show',$show);
            $this->assign('brandList',$brandList);
            $this->display('brandList');
        }
		
		public function item_sort(){
			$arr=I('ids');
			$arr=explode(',',$arr);echo \count($arr);
			for($i=0;$i<\count($arr);$i++){
				M('spec_item')->where('id='.$arr[$i])->setField('sort',$i);
			}
		}
	
    /**
     * 添加修改编辑  商品品牌
     */
    public  function addEditBrand(){        
            $id = I('id',0);
            $model = M("Brand");           
            if(IS_POST)
            {
                    $model->create();                    
                    if($id){
                        $model->save();
                    }                        
                    else
                    {
                        $model->store_id = STORE_ID;
                        $model->status = 1;
                        $id = $model->add();
                    }                        
                    $this->success("操作成功!!!",U('Goods/brandList',array('p'=>$_GET['p'])));               
                    exit;
            }           
           $cat_list = M('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单
           $this->assign('cat_list',$cat_list);
           $brand = $model->where("id = $id")->find();           
           $this->assign('brand',$brand);
           $this->display('_brand');           
    }    
    
    /**
     * 删除品牌
     */
    public function delBrand()
    {           
        $model = M("Brand"); 
        $id = I('id');
        $model->where("id = $id and store_id = ".STORE_ID)->delete();
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
        $this->ajaxReturn(json_encode($return_arr));
    }    
    
	public function brand_info(){
		$id = I('id',0);
		$cat_list = M('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单
		$this->assign('cat_list',$cat_list);
		if($id>0){
			$brand = M("Brand")->find($id);
			$this->assign('brand',$brand);
		}
		$this->display();
	}
	
	public function brand_save(){
		$data = I('post.');
		if($data['act'] == 'del'){
			$goods_count = M('Goods')->where("brand_id = {$data['id']}")->count('1');
			if($goods_count) respose(array('stat'=>'fail','msg' =>'此品牌有商品在用不得删除!'));
			$r = M('brand')->where('id='.$data['id'])->delete();
			if($r){
				respose(array('stat'=>'ok'));
			}else{
				respose(array('stat'=>'fail','msg'=>'操作失败'));
			}
		}else{
			if(empty($data['id'])){
				$data['store_id'] = STORE_ID;
				$r = M('brand')->add($data);
			}else{
				$r = M('brand')->where('id='.$data['id'])->save($data);
			}
		}
		if($r){
			$this->success("操作成功",U('Store/brand_list'));
		}else{
			$this->error("操作失败",U('Store/brand_list'));
		}
	}    
        
    /**
     * 删除商品相册图
     */
    public function del_goods_images()
    {
        $path = I('filename','');
        $goods_images = M('goods_images')->where(array('image_url'=>$path))->select();
        foreach($goods_images as $key=>$val)
        {
            $goods = M('goods')->where(array('goods_id'=>$goods_images[$key]['goods_id']))->find();
            if($goods['store_id'] == STORE_ID){
                M('goods_images')->where(array('img_id'=>$goods_images[$key]['img_id']))->delete();
            }
        }
    }
	
	public function chakan_kucun()
	{		
	    $goods_id = I('goods_id');
		$goods_name = I('goods_name');
		$model = M("spec_goods_price a"); 
		$where='a.store_id='.STORE_ID;
		$where.=$goods_id!='' ?' and a.goods_id in('.$goods_id.') ':'';
		$where.=$goods_name!='' ?' and b.goods_name like "%'.$goods_name.'%" ':'';

		$count=$model
		->field('a.*,b.goods_name')
		->join('ty_goods b on a.goods_id=b.goods_id')
		->where($where)->count();
		$Page  = new Page($count,20);
		$show  = $Page->show(); 
		
	    $goods_list = $model
		->field('a.*,b.goods_name')
		->join('ty_goods b on a.goods_id=b.goods_id')
		->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();

	$this->assign('goods_list',$goods_list);
	$this->assign('show',$show);
	$this->display();
	}

    /**
     *  修改价格商品列表
     */
    public function ajaxGoodsEditList(){
        $where = "a.store_id = ".STORE_ID; // 搜索条件
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;
        (I('store_cat_id1') !== '') && $where = "$where and store_cat_id1 = ".I('store_cat_id1');
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale');
        $goods_state = I('goods_state'); // 商品状态  0待审核 1审核通过 2审核失败  3违规下架

        ($goods_state !== '') && $where = "$where and goods_state in ($goods_state) ";

        //tianxin100  新增商品回收站功能
        $is_delete =  $_GET["is_delete"]; // 商品状态  0待审核 1审核通过 2审核失败  3违规下架
        if($is_delete){
            $where = "$where and is_delete = $is_delete ";
        }else{

            $where = "$where and is_delete = 0 ";
        }
        //tianxin100  新增商品回收站功能


        // 关键词搜索
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        $label = I('label') ? trim(I('label')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }

        if($label)
        {
            $where = "$where and (label like '%$label%')" ;
        }

        $where .= " and is_pint = 0 ";
        $model = M('Goods');

        $count = $model->alias('a')->join('ty_spec_goods_price b on a.goods_id = b.goods_id','left')->where($where)->count();

        $Page  = new AjaxPage($count,100);

        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        //是否从缓存中获取Page
        if(session('is_back')==1){
            $Page = getPageFromCache();
            //重置获取条件
            delIsBack();
        }

        $goodsList = $model->alias('a')->field('a.*,b.key,b.key_name,b.price as item_price,b.store_count,b.sku,b.spu')->join('ty_spec_goods_price b on a.goods_id = b.goods_id','left')->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();

//        foreach($goodsList as $key=>$v){
//            $goodsList[$key]['kucun']=M('spec_goods_price')->where('goods_id='.$v['goods_id'])->order('store_count asc')->getField('store_count');
//            $goodsList[$key]['zhuangtai']=M('store_msg')->where('goods_id='.$v['goods_id'])->order('sm_id desc')->getField('content');
//
//
//        }

        cachePage($Page);
        $show = $Page->show();
        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('p',$_GET['p']);
        $this->display();
    }


    /**
     * 批量修改价格
     */
    public function batch_edit_price()
    {
        if(IS_POST){
            $store_id = STORE_ID;

        }


        checkIsBack();
        $store_goods_class_list = M('store_goods_class')->where("parent_id = 0 and store_id = ".STORE_ID)->select();
        $this->assign('store_goods_class_list',$store_goods_class_list);
        $this->assign('p',isset($_GET['p']) ? $_GET['p'] : 1);

        $this->display();
    }

    public function batch_add2()
    {
        if(IS_POST){
            $excelFile = $_FILES['file']['tmp_name'];
            $data = $this->readFromExcel($excelFile);
            foreach($data['data'] as $item){
                $fenbu_id = M('fenbu')->where(['fenbu_name'=>$item[6]])->getField('fenbu_id');
                if($fenbu_id){
                    M('users')->where(['user_id'=>$item[0]])->save(['fenbu_id'=>$fenbu_id,'biaoshi_xian'=>$item[4]]);
                }
            }
            echo "同步完成";
        }
        $this->display();
    }


    /**
     * 批量导入商品
     */
    public function batch_add()
    {
        if(STORE_ID == 22687){
            return $this->batch_add2();
        }
        if(IS_POST){
            $store_id = STORE_ID;
            $store = M('store')->where(['store_id'=>$store_id])->find();
            $excelFile = $_FILES['file']['tmp_name'];
            $data = $this->readFromExcel($excelFile);
            if($data && $data['data']){
                $errorNo = [];
                foreach($data['data'] as $item){
                    try{
                        if($item && $item[0]){ //有数据才添加

                            Db::startTrans(); //开启事务

                            //第一步添加产品类别
                            $goodsTypeId = M('goods_type')->where(['name'=>$item[7],'store_id'=>$store_id])->getField('id');
                            if(!$goodsTypeId){
                                $goodsTypeId = M('goods_type')->add(['name'=>$item[7],'store_id'=>$store_id]);
                            }

                            //第二步添加产品
                            $goodsId = M('goods')->where(['goods_name'=>$item[0],'store_id'=>$store_id,'is_on_sale'=>1])->getField('goods_id');
                            if(!$goodsId){ //不重复添加商品
                                //查找分类
                                $cate1 = M('goods_category')->where(['name'=>$item[1]])->getField('id');
                                $cate2 = M('goods_category')->where(['name'=>$item[2]])->getField('id');
                                $cate3 = M('goods_category')->where(['name'=>$item[3]])->getField('id');
                                $goodsData = [
                                    'goods_name'=>$item[0],
                                    'cat_id1'=>$cate1 ?? 0,
                                    'cat_id2'=>$cate2 ?? 0,
                                    'cat_id3'=>$cate3 ?? 0,
                                    'store_count'=>8888,
                                    'shop_price'=>$item[5],
                                    'goods_type'=>$goodsTypeId,
                                    'is_real'=>1,
                                    'is_on_sale'=>1,
                                    'on_time'=>time(),
                                    'sort'=>50,
                                    'store_id'=>$store_id,
                                    'goods_state'=>0,
                                    'unit'=>$item[4],
                                    'points'=>$store['koudian'],
                                    'sales_sum'=>$store['sale_num'],
                                    'yijia_quyu'=>$store['yijia_quyu'],
                                ];
                                $goodsId = M('goods')->add($goodsData);
                            }

                            //第三步添加规格
                            if($item && $item[8]){
                                $specs = explode('/',$item[8]);
                                foreach($specs as $key=>$spec){
                                    $goodsSpec = M('spec')->where(['name'=>$spec,'store_id'=>$store_id,'goods_type_id'=>$goodsTypeId])->find();
                                    if(!$goodsSpec){
                                        $specData = ['name'=>$spec,'store_id'=>$store_id,'goods_type_id'=>$goodsTypeId,'order'=>$key,'search_index'=>1];
                                        M('spec')->add($specData);
                                    }
                                }

                                if($item && $item[9]){
                                    $goodsSpecId1 = M('spec')->where(['name'=>$specs[0],'store_id'=>$store_id,'goods_type_id'=>$goodsTypeId])->getField('id');
                                    $goodsSpecItemId1 = M('spec_item')->where(['spec_id'=>$goodsSpecId1,'item'=>$item[9],'store_id'=>$store_id,'goods_id'=>$goodsId])->getField('id');
                                    if(!$goodsSpecItemId1){
                                        $goodsSpecItemId1 = M('spec_item')->add(['spec_id'=>$goodsSpecId1,'item'=>$item[9],'store_id'=>$store_id,'goods_id'=>$goodsId,'sort'=>0]);
                                    }
                                }else{
                                    $goodsSpecId1 = M('spec')->where(['name'=>$specs[0],'store_id'=>$store_id,'goods_type_id'=>$goodsTypeId])->getField('id');
                                    $goodsSpecItemId1 = M('spec_item')->where(['spec_id'=>$goodsSpecId1,'item'=>$item[4],'store_id'=>$store_id,'goods_id'=>$goodsId])->getField('id');
                                    if(!$goodsSpecItemId1){
                                        $goodsSpecItemId1 = M('spec_item')->add(['spec_id'=>$goodsSpecId1,'item'=>$item[4],'store_id'=>$store_id,'goods_id'=>$goodsId,'sort'=>0]);
                                    }
                                }

                                if(count($specs) >= 2 && $item && $item[10]){
                                    $goodsSpecId2 = M('spec')->where(['name'=>$specs[1],'store_id'=>$store_id,'goods_type_id'=>$goodsTypeId])->getField('id');
                                    $goodsSpecItemId2 = M('spec_item')->where(['spec_id'=>$goodsSpecId2,'item'=>$item[10],'store_id'=>$store_id,'goods_id'=>$goodsId])->getField('id');
                                    if(!$goodsSpecItemId2){
                                        $goodsSpecItemId2 = M('spec_item')->add(['spec_id'=>$goodsSpecId2,'item'=>$item[10],'store_id'=>$store_id,'goods_id'=>$goodsId,'sort'=>1]);
                                    }
                                }

                                if(count($specs) >= 3 && $item && $item[11]){
                                    $goodsSpecId3 = M('spec')->where(['name'=>$specs[2],'store_id'=>$store_id,'goods_type_id'=>$goodsTypeId])->getField('id');
                                    $goodsSpecItemId3 = M('spec_item')->where(['spec_id'=>$goodsSpecId3,'item'=>$item[11],'store_id'=>$store_id,'goods_id'=>$goodsId])->getField('id');
                                    if(!$goodsSpecItemId3){
                                        $goodsSpecItemId3 = M('spec_item')->add(['spec_id'=>$goodsSpecId3,'item'=>$item[11],'store_id'=>$store_id,'goods_id'=>$goodsId,'sort'=>2]);
                                    }
                                }

                                $keyIds = $goodsSpecItemId1;
                                $keyStrs = $specs[0].':'.$item[9];

                                if(count($specs) >= 2 && $item && $item[10]){
                                    $keyIds = $keyIds.'_'.$goodsSpecItemId2;
                                    $keyStrs = $keyStrs.' '.$specs[1].':'.$item[10];
                                }
                                if(count($specs) >= 3 && $item && $item[11]){
                                    $keyIds = $keyIds.'_'.$goodsSpecItemId3;
                                    $keyStrs = $keyStrs.' '.$specs[2].':'.$item[11];
                                }

                                $keyIdsData = explode('_',$keyIds); //跟进原有的规则进行规格排序
                                sort($keyIdsData);
                                $keyIds = implode('_',$keyIdsData);

                                $specGoodsPrice = M('spec_goods_price')->where(['goods_id'=>$goodsId,'key'=>$keyIds,'store_id'=>$store_id,'price'=>$item[5]])->find();
                                if(!$specGoodsPrice){
                                    M('spec_goods_price')->add(['goods_id'=>$goodsId,'key'=>$keyIds,'key_name'=>$keyStrs,'price'=>$item[5],'store_count'=>$item[12],'store_id'=>$store_id,'qipi_num'=>$item[13],'sku'=>$item[14]]);
                                }
                            }

                            Db::commit(); //事务提交
                        }
                    }catch(Exception $e){
                        Db::rollback();//事务回滚
                        Log::record($e->getMessage(),'ERR');
                        $errorNo[] = $item[0];
                    }
                }

            }
            exit;

        }
        $this->display();
    }


    /**
     * 读取 excel 文件内容
     * @param string    $excelFile 文件路径
     * @param int       $startRow 开始行
     * @param null      $endRow 结束行
     * @return array
     * @throws PHPExcel_Reader_Exception
     */
    protected function readFromExcel($excelFile, $startRow = 2, $endRow = null)
    {
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");
        import("Org.Util.PHPExcel.Writer.Excel2007");

        $inputFileType = PHPExcel_IOFactory::identify($excelFile);

        try {
            $excelReader = PHPExcel_IOFactory::createReader($inputFileType);
            $phpexcel    = $excelReader->load($excelFile);
            $activeSheet = $phpexcel->getActiveSheet();
            if (!$endRow) {
                $endRow = $activeSheet->getHighestRow(); //总行数
            }

            $highestColumn      = $activeSheet->getHighestColumn(); //最后列数所对应的字母，例如第2行就是B
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); //总列数

            $data = array();

            for ($row = $startRow; $row <= $endRow; $row++) {
                for ($col = 0; $col < $highestColumnIndex; $col++) {
                    $data[$row][] = (string) $activeSheet->getCellByColumnAndRow($col, $row)->getCalculatedValue();
                }
            }
        } catch (Exception $e) {
            $arr['code'] = 1001;
            $arr['msg'] = $e->getMessage();
            return $arr;
        }

        $arr['code'] = '1000';
        $arr['data'] = $data;
        return $arr;
    }


    /**
     * 商品批量操作 by 众创织梦-邵
     * @param $id
     */
    public function goods_actions_item(){

        $keys = I('keys');
        $floating = I('val');
        $action = I('action');
        $where['key'] = ['in',explode(',',$keys)];

        if($floating){
            if($action == 'store_count'){
                M('spec_goods_price')->where($where)->save(['store_count'=>$floating]);
            }

            if($action == 'floating'){
               $goods_id = [];
               $goods =  M('spec_goods_price')->where($where)->group('goods_id')->select();
               foreach ($goods as $good){
                   $goods_id[] =$good['goods_id'];
               }
                $where2['goods_id'] = ['in',$goods_id];
                M('goods')->where($where2)->save(['floating'=>$floating]);

            }
            echo '0';
        }
    }


    /**
     * 搜索产品
     */
    public function search_goods()
    {
        $search_key = trim(I('search_key'));

        $where="(goods_name like'%$search_key%' or goods_id like'%$search_key%' )  and goods_state = 1 and is_on_sale = 1  and store_id=".STORE_ID;

        $list = M('goods')->where($where)->select();

        if(empty($list)){
            echo \json_encode([
                'code'=>-1
            ]);
            return false;
        }

        foreach($list as $v){
            $list_s.='<li rel="'.$v['goods_id'].'"  title="'.$v['goods_name'].'" >'.$v['goods_id'].'：'.$v['goods_name'].'</li>';
        }
        echo \json_encode([
            'code'=>'200',
            'selects'=>$list_s
        ]);
        exit;
    }


    /**
     * 导出产品
     */
    public function export_goods(){

        $where = "a.store_id = ".STORE_ID; // 搜索条件
        (I('store_cat_id1') !== '') && $where = "$where and store_cat_id1 = ".I('store_cat_id1');
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale');

        //tianxin100  新增商品回收站功能


        // 关键词搜索
        $key_word = I('key_word') ? trim(I('key_word')) : '';

        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }

        $where .= " and is_pint = 0 ";
        $model = M('Goods');

       
        $goodsList = $model->alias('a')->field('a.goods_name,a.goods_id,b.key_name,b.price as item_price,b.store_count,b.sku,b.key')->join('ty_spec_goods_price b on a.goods_id = b.goods_id','left')->where($where)->order('goods_id desc')->select();

        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">商品ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:200px;">商品名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:250px;">规格名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;" width="*">单价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;" width="*">库存</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;" width="*">sku</td>';
        $strTable .= '</tr>';

        foreach($goodsList as $k=>$val){
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['goods_id'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['goods_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['key_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['item_price'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['store_count'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['sku'].'</td>';
            $strTable .= '</tr>';
        }

        $strTable .='</table>';
        unset($goodsList);
        downloadExcel($strTable,'goods');
        exit();
    }
}